/**
 * Title:        批量提交的条件检测
 * Company:      泛微软件
 */

package checkWithCondit;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import weaver.conn.RecordSet;
import weaver.general.Util;

import general.BaseBean;

public class BatchSubmitCheck extends BaseBean implements checkWithConBase  {

    @Override
    public String getPopupUrl() {
        return "/flowtoolbar/checkWithCondit/RequestCondition.jsp";
    }

    @Override
    public JSONObject checkData(HashMap dataMap) {
        setRecordSet();
        List resultList = new ArrayList();
        String result = resultOk;

        int requestid = -1;
        int nodeid = -1;
        int userid = -1;
        String workflowid = "";
        String isremark = "0";
        String workflowname = "";
        if(!dataMap.containsKey("requestid") || "".equals(dataMap.get("requestid"))){
            result = resultERROR;
            resultList.add("请选择流程请求。");
            return formatReturnJsonCheck(result, resultList, this);
        }
        requestid = Util.getIntValue(Util.null2String(dataMap.get("requestid")),-1);
        
        if(nodeid == -1){
            recordSet.executeSql(" select c.userid, c.workflowid, c.isremark, c.nodeid, b.workflowname from workflow_currentoperator c left join workflow_base b on c.workflowid = b.id where c.requestid = " + requestid + " and c.isremark = '0'");
            if(recordSet.next()){
                userid = recordSet.getInt("userid");
                workflowid = recordSet.getString("workflowid");
                nodeid = recordSet.getInt("nodeid");
                workflowname = recordSet.getString("workflowname");
            }else{
                isremark = "1";
                //流程已归档无需当前操作节点操作
                resultList.add("检测正常，该流程无当前无需操作，请检查是否已经归档!");
            }
        }
        
        String flag = "false";
        if (isremark.equals("0")) {
            if ("1".equals(getWFMultiSubmit(workflowid))){
                flag = "true";
            }else{
                Map resultMap = new HashMap<String,String>();
                resultMap.put("showMessage", formatMessage(workflowname, "路径中未开启允许批量提交，所以选择框无法勾选！"));
                resultMap.put("workflowid", workflowid);
                resultMap.put("buttonname", "开启允许批量提交");
                resultList.add(resultMap);
                result = resultNeedFix;
            }
                
            if (flag.equals("true")) {
                RecordSet rs = new RecordSet();
                rs.executeSql("select nodename from workflow_nodebase where id = " + nodeid);
                //节点名称
                String nodename = rs.getString("nodename");
                
                //判断当前节点对应模板是否有必填字段
                if (flag.equals("true") && haveMustInput(requestid,nodeid)) {
                    flag = "false";
                    Map resultMap = new HashMap<String,String>();
                    resultMap.put("showMessage",formatMessage(workflowname, "路径中当前操作节点：" + nodename + " 对应模板中存在必填字段，所以无法批量选择提交！"));
                    resultMap.put("linkurl","/workflow/workflow/addwfnodefield.jsp?design=0&ajax=1&wfid=" + Integer.parseInt(workflowid) + "&nodeid=" + nodeid + "#");
                    resultMap.put("linkname","修改模板请点击此处进行设置");
                    resultList.add(resultMap);
                    result = resultNeedFix;
                } else {
                    //判断当前节点对应模板必须新增明细是否有值
                    if (haveDetailMustAdd(workflowid, requestid,nodeid)) {
                        flag = "true";
                    } else {
                        //开启必须新增明细且明细无数据返回false
                        flag = "false";
                        Map resultMap = new HashMap<String,String>();
                        resultMap.put("showMessage",formatMessage(workflowname, "路径中所在当前操作节点：" + nodename + " 对应模板中存在必须新增明细，明细中没有数据，所以无法批量选择提交！"));
                        resultMap.put("linkurl","/workflow/workflow/addwfnodefield.jsp?design=0&ajax=1&wfid=" + Integer.parseInt(workflowid) + "&nodeid=" + nodeid + "#");
                        resultMap.put("linkname","修改模板请点击此处进行设置");
                        resultList.add(resultMap);
                        result = resultNeedFix;
                    }
                }
            }
        }
        if(isremark.equals("0") && result.equals(resultOk)){
            resultList.add("检测正常，该路径当前节点可以批量选择提交!");
        }
        
        return formatReturnJsonCheck(result, resultList, this);
    }
    
    /**
     * 是否开启允许批量提交
     * @param wfid
     * @return 1-开启
     */
    private String getWFMultiSubmit(String wfid){
        String returnstr = "";
        recordSet.executeSql("select multiSubmit from WORKFLOW_BASE WHERE ID = " + Integer.parseInt(wfid));
        while (recordSet.next()) {
            returnstr = Util.null2String(recordSet.getString("multiSubmit"));
        }
        return returnstr;
    }
    
    /**
     * 是否开启必须新增明细且明细有数据
     * @param workflowid
     * @param requestid
     * @param nodeid
     * @return false ——开启必须新增明细且明细无数据返回false
     */
    private boolean haveDetailMustAdd(String workflowid,int requestid,int nodeid) {
        boolean flag = true; 
        String sql = "";
        String checksql = "";
        int isbill = 0;
        int formid = 0;
        int groupid= 0;
        int checks = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        RecordSet rs2 = new RecordSet();
        sql = "select formid,isbill from workflow_base where id=" + workflowid;
        rs.executeSql(sql);
        if (rs.next()){
            formid = rs.getInt(1);
            isbill = rs.getInt(2);
        }
        //修改，主要是针对客户复制了明细表，然后直接删除了明细字段
        if(formid > 0 && isbill == 0){ //老表单
              checksql = "SELECT count(fieldid) FROM workflow_formfield WHERE formid="+formid+" and isdetail is not null";
              rs.executeSql(checksql);
              if (rs.next()){
                  checks = rs.getInt(1);
              }
              if (checks>0) {
                  //检查当前节点 是否设置了 必须新增明细
                  sql = "select groupid from workflow_NodeFormGroup where isneed=1 and nodeid=" + nodeid;
                  rs1.executeSql(sql);
                  while (rs1.next()){
                      groupid = rs.getInt(1);
                      //判断是新表单还是老表单，明细表不一样
                      if(formid > 0 && isbill == 0){//老表单
                          //检查明细是否有数据
                          sql = "select id from workflow_formdetail where requestid=" + requestid + " and groupid=" + groupid;
                          rs2.executeSql(sql);
                          if (rs2.next()) {
                              
                          }else{
                              return false;
                          }
                      }
                      if(formid < 0 && isbill == 1){//新表单
                          int dt = groupid + 1;
                          int mainT = -formid;
                          //检查明细是否有数据
                          sql = "select id from formtable_main_" + mainT + "_dt"+ dt +" where mainid=(select id from formtable_main_" + mainT + " where requestid=" + requestid + ")";
                          rs2.executeSql(sql);
                          if (rs2.next()) {
                              
                          }else{
                              return false;
                          }
                      }
                  }
              }else{
                  
              }
          }
        if(formid < 0 && isbill == 1){//新表单
              checksql = "select COUNT(id) from workflow_billfield where billid="+formid+"  AND viewtype =1";
              rs.executeSql(checksql);
              if (rs.next()){
                  checks = rs.getInt(1);
              }
              if (checks>0) {
                  //检查当前节点 是否设置了 必须新增明细
                  sql = "select groupid from workflow_NodeFormGroup where isneed=1 and nodeid=" + nodeid;
                  rs1.executeSql(sql);
                  while (rs1.next()){
                      groupid = rs.getInt(1);
                      //判断是新表单还是老表单，明细表不一样
                      if(formid > 0 && isbill == 0){//老表单
                          //检查明细是否有数据
                          sql = "select id from workflow_formdetail where requestid=" + requestid + " and groupid=" + groupid;
                          rs2.executeSql(sql);
                          if (rs2.next()) {
                              
                          }else{
                              return false;
                          }
                      }
                      if(formid < 0 && isbill == 1){//新表单
                          int dt = groupid + 1;
                          int mainT = -formid;
                          //检查明细是否有数据
                          sql = "select id from formtable_main_" + mainT + "_dt"+ dt +" where mainid=(select id from formtable_main_" + mainT + " where requestid=" + requestid + ")";
                          rs2.executeSql(sql);
                          if (rs2.next()) {
                              
                          }else{
                              return false;
                          }
                      }
                  }
              }else{
                  
              }
          }
        return flag;
   }
    
    private boolean haveMustInput(int requestid,int nodeid) {
        boolean flag = false; 
        String sql = "select currentnodeid,workflowid from workflow_requestbase where requestid=" + requestid;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        rs.executeSql(sql);
        if (rs.next()) {
            int workflowid = rs.getInt(2);
            sql = "select ismode,showdes,printdes,toexcel from workflow_flownode where workflowid=" + workflowid + " and nodeid=" + nodeid;
            rs.executeSql(sql);
            if (rs.next()) {
                String ismode = Util.null2String(rs.getString("ismode"));
                int showdes = Util.getIntValue(Util.null2String(rs.getString("showdes")), 0);
                int modeid = 0;
                int isbill = 0;
                int formid = 0;
                String sqlwhere = "";
                String viewtablename = "workflow_nodeform";
                sql = "select formid,isbill from workflow_base where id=" + workflowid;
                rs.executeSql(sql);
                if (rs.next()) {
                    formid = rs.getInt(1);
                    isbill = rs.getInt(2);
                }
                if (ismode.equals("1") && showdes != 1) {
                    sql = "select id from workflow_nodemode where isprint='0' and workflowid=" + workflowid + " and nodeid=" + nodeid;
                    rs.executeSql(sql);
                    if (rs.next()) {
                        modeid = rs.getInt("id");
                    } else {
                        sql = "select id from workflow_formmode where isprint='0' and formid=" + formid + " and isbill=" + isbill;
                        rs.executeSql(sql);
                        if (rs.next()) {
                            modeid = rs.getInt("id");
                        }
                    }
                }
                //模板模式
                if (modeid > 0) {
                    viewtablename = "workflow_modeview";
                } 
                //System.out.println("formid:"+formid+",isbill="+isbill);
                //表单
                if (isbill == 0) {
                    //主字段
                    sql = "select ff.fieldname,ff.fielddbtype from " + viewtablename + " nf ,workflow_formdict ff where nf.fieldid=ff.id and nf.nodeid=" + nodeid + " and nf.ismandatory=1 and nf.fieldid>0 ";
                    rs.executeSql(sql);
                    while (rs.next()) {
                        String fielddbtype = Util.null2String(rs.getString(2));
                        if (fielddbtype.toLowerCase().indexOf("int") > -1 || fielddbtype.toLowerCase().indexOf("float") > -1 || fielddbtype.toLowerCase().indexOf("number") > -1) {
                            if (sqlwhere.equals(""))
                                sqlwhere = rs.getString(1) + " is null";
                            else
                                sqlwhere += " or " + rs.getString(1) + " is null";
                        } else { 
                            if(rs.getDBType().equals("sqlserver")){
                                String _t = " convert(varchar,"+rs.getString(1)+") ";
                                if (sqlwhere.equals(""))
                                    sqlwhere = _t + " is null or " + _t + "='' or " +_t + "=' '";
                                else
                                    sqlwhere += " or " + _t + " is null or " + _t + "='' or " + _t + "=' '";
                            }else{
                                if (sqlwhere.equals("")){
                                    if (fielddbtype.toLowerCase().indexOf("clob") > -1){
                                        sqlwhere = rs.getString(1) + " is null or dbms_lob.getlength("+rs.getString(1)+") = 0";
                                    }else{
                                        sqlwhere = rs.getString(1) + " is null or " + rs.getString(1) + "='' or " + rs.getString(1) + "=' '";
                                    }
                                }else{
                                    if (fielddbtype.toLowerCase().indexOf("clob") > -1){
                                        sqlwhere += " or (" +rs.getString(1) + " is null or dbms_lob.getlength("+rs.getString(1)+") = 0)";
                                    }else{
                                        sqlwhere += " or " + rs.getString(1) + " is null or " + rs.getString(1) + "='' or " + rs.getString(1) + "=' '";
                                    }
                                }
                            }
                        }
                    }
                    if (!sqlwhere.equals("")) {
                        sql = "select requestid from workflow_form where requestid=" + requestid + " and (" + sqlwhere + ")";
                        rs.executeSql(sql); 
                        if (rs.next()) {
                            return true;
                        }
                    } 
                    //明细字段
                    sqlwhere = "";
                    sql = "select ff.fieldname,ff.fielddbtype from " + viewtablename + " nf ,workflow_formdictdetail ff where nf.fieldid=ff.id and nf.nodeid=" + nodeid + " and nf.ismandatory=1 and nf.fieldid>0 ";
                    rs.executeSql(sql);
                    while (rs.next()) {
                        String fielddbtype = Util.null2String(rs.getString(2));
                        if (fielddbtype.toLowerCase().indexOf("int") > -1 || fielddbtype.toLowerCase().indexOf("float") > -1 || fielddbtype.toLowerCase().indexOf("number") > -1) {
                            if (sqlwhere.equals(""))
                                sqlwhere = rs.getString(1) + " is null";
                            else
                                sqlwhere += " or " + rs.getString(1) + " is null";
                        } else {
                            if(rs.getDBType().equals("sqlserver")){
                                String _t = " convert(varchar,"+rs.getString(1)+") ";
                                if (sqlwhere.equals(""))
                                    sqlwhere = _t + " is null or " + _t + "='' or " +_t + "=' '";
                                else
                                    sqlwhere += " or " + _t + " is null or " + _t + "='' or " + _t + "=' '";
                            }else{
                                if (sqlwhere.equals("")){
                                    if (fielddbtype.toLowerCase().indexOf("clob") > -1){
                                        sqlwhere = rs.getString(1) + " is null or dbms_lob.getlength("+rs.getString(1)+") = 0";
                                    }else{
                                        sqlwhere = rs.getString(1) + " is null or " + rs.getString(1) + "='' or " + rs.getString(1) + "=' '";
                                    }
                                }else{
                                    if (fielddbtype.toLowerCase().indexOf("clob") > -1){
                                        sqlwhere += " or (" +rs.getString(1) + " is null or dbms_lob.getlength("+rs.getString(1)+") = 0)";
                                    }else{
                                        sqlwhere += " or " + rs.getString(1) + " is null or " + rs.getString(1) + "='' or " + rs.getString(1) + "=' '";
                                    }
                                }
                            }
                        }
                    }
                    if (!sqlwhere.equals("")) {
                        sql = "select requestid from workflow_formdetail where requestid=" + requestid + " and (" + sqlwhere + ")";
                        rs.executeSql(sql); 
                        if (rs.next()) {
                            return true;
                        }
                    }
                } else if (isbill == 1) {   //单据
                    //主字段
                    String maintablename = "";
                    String detailkey = "";
                    sql = "select tablename,detailkeyfield from workflow_bill where id=" + formid;
                    rs.executeSql(sql);
                    if (rs.next()) {
                        maintablename = rs.getString(1);
                        detailkey = Util.null2String(rs.getString(2));
                    }
                    if (detailkey.equals("")) detailkey = "mainid";
                    sql = "select ff.fieldname,ff.fielddbtype from " + viewtablename + " nf ,workflow_billfield ff where (ff.viewtype is null or ff.viewtype=0) and nf.fieldid=ff.id and ff.billid=" + formid + " and nf.nodeid=" + nodeid + " and nf.ismandatory=1 and nf.fieldid>0 ";
                    rs.executeSql(sql);
                    while (rs.next()) {
                        String fielddbtype = Util.null2String(rs.getString(2));
                        if (fielddbtype.toLowerCase().indexOf("int") > -1 || fielddbtype.toLowerCase().indexOf("float") > -1 || fielddbtype.toLowerCase().indexOf("number") > -1) {
                            if (sqlwhere.equals(""))
                                sqlwhere = rs.getString(1) + " is null";
                            else
                                sqlwhere += " or " + rs.getString(1) + " is null";
                        } else {
                            if(rs.getDBType().equals("sqlserver")){
                                String _t = " convert(varchar,"+rs.getString(1)+") ";
                                if (sqlwhere.equals(""))
                                    sqlwhere = _t + " is null or " + _t + "='' or " +_t + "=' '";
                                else
                                    sqlwhere += " or " + _t + " is null or " + _t + "='' or " + _t + "=' '";
                            }else{
                                if (sqlwhere.equals("")){
                                    if (fielddbtype.toLowerCase().indexOf("clob") > -1){
                                        sqlwhere = rs.getString(1) + " is null or dbms_lob.getlength("+rs.getString(1)+") = 0";
                                    }else{
                                        sqlwhere = rs.getString(1) + " is null or " + rs.getString(1) + "='' or " + rs.getString(1) + "=' '";
                                    }
                                }else{
                                    if (fielddbtype.toLowerCase().indexOf("clob") > -1){
                                        sqlwhere += " or (" +rs.getString(1) + " is null or dbms_lob.getlength("+rs.getString(1)+") = 0)";
                                    }else{
                                        sqlwhere += " or " + rs.getString(1) + " is null or " + rs.getString(1) + "='' or " + rs.getString(1) + "=' '";
                                    }
                                }
                            }
                        }
                    }
                    if (!sqlwhere.equals("")) {
                        sql = "select requestid from " + maintablename + " where requestid=" + requestid + " and (" + sqlwhere + ")";
                        rs.executeSql(sql);
                        if (rs.next()) {
                            return true;
                        }
                    }
                    //明细字段
                    sql = "select tablename from workflow_billdetailtable where billid=" + formid;
                    rs1.executeSql(sql);
                    while (rs1.next()) {
                        String detailtablename = rs1.getString(1);
                        sqlwhere = "";
                        sql = "select ff.fieldname,ff.fielddbtype from " + viewtablename + " nf ,workflow_billfield ff where ff.viewtype=1 and nf.fieldid=ff.id and ff.billid=" + formid + " and ff.detailtable='" + detailtablename + "' and nf.nodeid=" + nodeid + " and nf.ismandatory=1 and nf.fieldid>0 order by ff.detailtable ";
                        rs.executeSql(sql);
                        while (rs.next()) {
                            String fielddbtype = Util.null2String(rs.getString(2));
                            if (fielddbtype.toLowerCase().indexOf("int") > -1 || fielddbtype.toLowerCase().indexOf("float") > -1 || fielddbtype.toLowerCase().indexOf("number") > -1) {
                                String _t = " "+detailtablename+"."+rs.getString(1)+" ";
                                if (sqlwhere.equals(""))
                                    sqlwhere = _t + " is null";
                                else
                                    sqlwhere += " or " + _t + " is null";
                            } else {
                                if(rs.getDBType().equals("sqlserver")){
                                    String _t = " convert(varchar,"+detailtablename+"."+rs.getString(1)+") ";
                                    if (sqlwhere.equals(""))
                                        sqlwhere = _t + " is null or " + _t + "='' or " +_t + "=' '";
                                    else
                                        sqlwhere += " or " + _t + " is null or " + _t + "='' or " + _t + "=' '";
                                }else{
                                    String _t = " "+detailtablename+"."+rs.getString(1)+" ";
                                    if (sqlwhere.equals("")){
                                        if (fielddbtype.toLowerCase().indexOf("clob") > -1){
                                            sqlwhere = _t + " is null or dbms_lob.getlength("+_t+") = 0";
                                        }else{
                                            sqlwhere = _t + " is null or " + _t+ "='' or " +_t + "=' '";
                                        }
                                    }else{
                                        if (fielddbtype.toLowerCase().indexOf("clob") > -1){
                                            sqlwhere += " or (" +_t + " is null or dbms_lob.getlength("+_t+") = 0)";
                                        }else{
                                            sqlwhere += " or " +_t + " is null or " + _t+ "='' or " +_t + "=' '";
                                        }
                                    }
                                }
                            }
                        }
                        if (!sqlwhere.equals("")) {
                            sql = "select " + maintablename + ".requestid from " + maintablename + "," + detailtablename + " where " + maintablename + ".id=" + detailtablename + "." + detailkey + " and " + maintablename + ".requestid=" + requestid + " and (" + sqlwhere + ")";
                            rs.executeSql(sql);
                            if (rs.next()) {
                                return true;
                            }
                        }
                    }
                    if (rs1.getCounts() < 1) {
                        sql = "select detailtablename from workflow_bill where id=" + formid;
                        rs.executeSql(sql);
                        if (rs.next()) {
                            String detailtablename = rs.getString(1);
                            sqlwhere = "";
                            sql = "select ff.fieldname,ff.fielddbtype from " + viewtablename + " nf , workflow_billfield ff where ff.viewtype=1 and nf.fieldid=ff.id and ff.billid=" + formid + " and ff.detailtable='" + detailtablename + "' and nf.nodeid=" + nodeid + " and nf.ismandatory=1 and nf.fieldid>0 order by ff.detailtable ";
                            rs.executeSql(sql);
                            while (rs.next()) {
                                String fielddbtype = Util.null2String(rs.getString(2));
                                if (fielddbtype.toLowerCase().indexOf("int") > -1 || fielddbtype.toLowerCase().indexOf("float") > -1 || fielddbtype.toLowerCase().indexOf("number") > -1) {
                                    String _t = " "+detailtablename+"."+rs.getString(1)+" ";
                                    if (sqlwhere.equals(""))
                                        sqlwhere = _t + " is null";
                                    else
                                        sqlwhere += " or " + _t + " is null";
                                } else {
                                    if(rs.getDBType().equals("sqlserver")){
                                        String _t = " convert(varchar,"+detailtablename+"."+rs.getString(1)+") ";
                                        if (sqlwhere.equals(""))
                                            sqlwhere = _t + " is null or " + _t + "='' or " +_t + "=' '";
                                        else
                                            sqlwhere += " or " + _t + " is null or " + _t + "='' or " + _t + "=' '";
                                    }else{
                                        String _t = " "+detailtablename+"."+rs.getString(1)+" ";
                                        if (sqlwhere.equals("")){
                                            if (fielddbtype.toLowerCase().indexOf("clob") > -1){
                                                sqlwhere = _t + " is null or dbms_lob.getlength("+_t+") = 0";
                                            }else{
                                                sqlwhere = _t + " is null or " + _t+ "='' or " +_t + "=' '";
                                            }
                                        }else{
                                            if (fielddbtype.toLowerCase().indexOf("clob") > -1){
                                                sqlwhere += " or (" +_t + " is null or dbms_lob.getlength("+_t+") = 0)";
                                            }else{
                                                sqlwhere += " or " +_t + " is null or " + _t+ "='' or " +_t + "=' '";
                                            }
                                        }
                                    }   
                                }
                            }
                            if (!sqlwhere.equals("")) {
                                sql = "select " + maintablename + ".requestid from " + maintablename + "," + detailtablename + " where " + maintablename + ".id=" + detailtablename + "." + detailkey + " and " + maintablename + ".requestid=" + requestid + " and (" + sqlwhere + ")";
                                rs.executeSql(sql);
                                if (rs.next()) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
        return flag;
    } 

    @Override
    public JSONObject fixData(HashMap dataMap) {
        setRecordSet();
        List resultList = new ArrayList();
        String result = "";
        if(dataMap != null && dataMap.get("workflowid") != null){
            String workflowid = (String) dataMap.get("workflowid");
            String divid =  (String)dataMap.get("divid");
            if(StringUtils.isNotEmpty(workflowid) && StringUtils.isNumeric(workflowid)){
                String updateSql = " update WORKFLOW_BASE set multiSubmit = 1 where ID = " + workflowid;
                (new BaseBean()).writeLog("BatchSubmitCheck fixData updateSql:" + updateSql);
                recordSet.executeUpdate(updateSql);
                Map resultMap = new HashMap<String,String>();
                resultMap.put("result",resultOk);
                resultMap.put("divid",divid);
                resultMap.put("fixMessage","开启允许批量选择成功");
                resultList.add(resultMap);
                return formatReturnJsonFix(result, resultList,this);
            }
        }
        return checkData(new HashMap());
    }

    @Override
    public String getClassDesc() {
        return "根据requestid来查询是否允许批量选择提交";
    }

    @Override
    public String getClassName() {
        return "批量选择提交的条件检测";
    }

}
